package com.cy;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.cy.service.RemoteProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@EnableFeignClients
@SpringBootApplication
public class ConsumerRunApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerRunApp.class, args);
    }


   //bean交给spring容器管理 让我们的spring cloud发现和管理 请求服务
    @Bean
    public RestTemplate restTemplate(){

        return new RestTemplate();
    }

    @RestController
    public class ConsumerController{
        //注入配置文件中数据信息

        @Value("${spring.application.name}")
        private String appName;

      //注入负载均衡的对象
        @Autowired
        private LoadBalancerClient client;

       @Autowired
       private RemoteProviderService service;

       //构造热点规则的前端访问路径
        @GetMapping("/com/findId")
        @SentinelResource("getId")//定义我们的热点资源名字
        public String doGetById(@RequestParam("id") Integer id){

            return "用户的id是:"+id;

        }


        //构建用户黑白名单的数据访问路径
        @GetMapping("/com/finduser")
        //@SentinelResource("getId")//定义我们的热点资源名字
        public String doGetByName(@RequestParam("name") String name){

            return "用户的名字是:"+name;

        }

       @GetMapping("echo3/{msg}")
       public String doFeignEcho(@PathVariable String msg){

      return service.echoMsg(msg);
       }


        //创建负载均衡的访问方法
        @GetMapping("/com/echo2")
        public String doGetEcho(){
            ServiceInstance instance=client.choose("sca-provider");
            String url=String.format("http://%s:%s/provider/echo/%s",instance.getHost(),instance.getPort(),appName );

           return restTemplate().getForObject(url, String.class);
        }



        //创建前端访问信息
      @GetMapping("/com/echo1")
      public String doGetProvider(){
       String url="http://localhost:8081/provider/echo/"+appName;
      return restTemplate().getForObject(url, String.class);
   }

    }

}
